/**
 * 
 */
package kulstats;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Query;

/**
 * @author steven
 *
 */
public class QuestionnaireManager {
	//private DAO dao;
	private static final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	private static final Map<String, ArrayList<String>> answerlistCache = new HashMap<String, ArrayList<String>>();
	//private static final Map<Integer, Question> templateqcache = new HashMap<Integer, Question>();
	
	public QuestionnaireManager() { //DAO dao) {
		//this.dao = dao;
	}
	
	
	private static Map<String, ArrayList<Integer>> questionIDMap = new HashMap<String, ArrayList<Integer>>();
	public static  Map<String, ArrayList<Integer>> getQuestionIDMap(){
		return questionIDMap;
	}
	
	
	public void addQuestionsToDB(List<Question> qlist, ActivityType atype, SpareTimeType sttype, LessonType ltype)
	{
		Key key = searchActivityKey(atype, sttype, ltype);
		// add new aquestion entities with the parent atype key
		for (int i = 0; i < qlist.size(); i++)
		{
			Question q = qlist.get(i);
			if (findQuestionByID(q.getQuestionID()) == null)
			{
				Entity qE = new Entity("AQuestion", key);
				qE.setProperty("QuestionID", q.getQuestionID());
				qE.setProperty("Question", q.getQuestion());
				qE.setProperty("AnswerList", q.getAnswerlist());
				datastore.put(qE);
			}
		}
	}
	
	public void addAnswerListToDB(List<String> alist, String listID)
	{
		Entity alE = new Entity("AList");
		if (findAnswerListByID(listID) == null)
		{
			alE.setProperty("ListID", listID);
			alE.setProperty("List", alist);
			datastore.put(alE);
		}
	}
	
	public void fillqmap()
	{// fill question map
		questionIDMap.put("Productiviteit", new ArrayList<Integer>());
		questionIDMap.get("Productiviteit").add(101);
		questionIDMap.get("Productiviteit").add(112);
		questionIDMap.get("Productiviteit").add(201);
		questionIDMap.put("Interesse", new ArrayList<Integer>());
		questionIDMap.get("Interesse").add(102);
		questionIDMap.put("Inspanning", new ArrayList<Integer>());
		questionIDMap.get("Inspanning").add(111);
		questionIDMap.get("Inspanning").add(201);
		questionIDMap.put("Ontspanning", new ArrayList<Integer>());
		questionIDMap.get("Ontspanning").add(301);
		questionIDMap.get("Ontspanning").add(321);
		questionIDMap.get("Ontspanning").add(331);
		questionIDMap.get("Ontspanning").add(341);
		questionIDMap.put("Slaap", new ArrayList<Integer>());
		questionIDMap.get("Slaap").add(311);
		questionIDMap.put("Maaltijd", new ArrayList<Integer>());
		questionIDMap.get("Maaltijd").add(302);
	}
	
	public void fill()
	{
		// add answer templates
		List<String> a1 = new ArrayList<String>();
		a1.add("1"); a1.add("2"); a1.add("3"); a1.add("4"); a1.add("5");
		addAnswerListToDB(a1, "a1");
		
		// add question templates
		List<Question> listlecture = new ArrayList<Question>();
		listlecture.add(new Question(101, "How well did you understand this lecture?","", "a1"));
		listlecture.add(new Question(102, "How interesting was this lecture?","", "a1"));
		addQuestionsToDB(listlecture, ActivityType.LESSON, null, LessonType.LECTURE);
		
		List<Question> listpractice = new ArrayList<Question>();
		listpractice.add(new Question(111, "How much effort did you put in this practice session?","", "a1"));
		listpractice.add(new Question(112, "How well did you understand this practice session?","", "a1"));
		addQuestionsToDB(listpractice, ActivityType.LESSON, null, LessonType.PRACTICE);
		
		List<Question> liststudy = new ArrayList<Question>();
		liststudy.add(new Question(201, "How much effort did you put in this self-study session?","", "a1"));
		liststudy.add(new Question(202, "How well did you understand this self-study session?","", "a1"));
		addQuestionsToDB(liststudy, ActivityType.STUDY, null, null);
		
		List<Question> liststeat = new ArrayList<Question>();
		liststeat.add(new Question(301, "How much did you enjoy your meal?","", "a1"));
		liststeat.add(new Question(302, "How heavy was your meal?","", "a1"));
		addQuestionsToDB(liststeat, ActivityType.SPARE_TIME, SpareTimeType.EAT, null);
		
		List<Question> liststsleep = new ArrayList<Question>();
		liststsleep.add(new Question(311, "How well did you sleep?","", "a1"));
		addQuestionsToDB(liststsleep, ActivityType.SPARE_TIME, SpareTimeType.SLEEP, null);
		
		List<Question> liststsport = new ArrayList<Question>();
		liststsport.add(new Question(321, "How well did you enjoy your sport activity?","", "a1"));
		addQuestionsToDB(liststsport, ActivityType.SPARE_TIME, SpareTimeType.SPORT, null);
		
		List<Question> liststhobby = new ArrayList<Question>();
		liststhobby.add(new Question(331, "How well did you enjoy your hobby?","", "a1"));
		addQuestionsToDB(liststhobby, ActivityType.SPARE_TIME, SpareTimeType.HOBBY, null);
		
		List<Question> liststparty = new ArrayList<Question>();
		liststparty.add(new Question(341, "How well did you enjoy the party?","", "a1"));
		addQuestionsToDB(liststparty, ActivityType.SPARE_TIME, SpareTimeType.PARTY, null);
	}
	
	private Key searchActivityKey(ActivityType atype, SpareTimeType sttype, LessonType ltype)
	{
		// search activitytype in db to retrieve key
		Query qry = new Query("QuestionnaireType");
		qry.addFilter("atype", Query.FilterOperator.EQUAL, atype.toString());
		if (sttype != null)
			qry.addFilter("sttype", Query.FilterOperator.EQUAL, sttype.toString());
		if (ltype != null)
			qry.addFilter("ltype", Query.FilterOperator.EQUAL, ltype.toString());
		List<Entity> pq = datastore.prepare(qry).asList(FetchOptions.Builder.withDefaults());
		Key key = null;
		if (!pq.isEmpty())
		{
			key = pq.get(0).getKey();
		}
		else
		{	// creates activitytype if it doesn't exist in db
			Entity atypeE = new Entity("QuestionnaireType");
			atypeE.setProperty("atype", atype.toString());
			if (sttype != null)
				atypeE.setProperty("sttype", sttype.toString());
			if (ltype != null)
				atypeE.setProperty("ltype", ltype.toString());
			datastore.put(atypeE);
			// TODO: debug if it returns correct key value
			key = atypeE.getKey();
		}
		return key;
	}
	
	public List<Question> manageQuestions(ActivityType atype, SpareTimeType sttype, LessonType ltype) {
		// search all question entities with ancestore of given activitytype
		Query qry = new Query("AQuestion");
		qry.addSort("QuestionID", Query.SortDirection.ASCENDING);
		qry.setAncestor(searchActivityKey(atype, sttype, ltype));
		List<Entity> pq = datastore.prepare(qry).asList(FetchOptions.Builder.withDefaults());
		
		// loops over results and passes the question objects from the entity to the list
		List<Question> list = new ArrayList<Question>();
		for (int i = 0; i < pq.size(); i++)
		{
			list.add(new Question(((Number)pq.get(i).getProperty("QuestionID")).intValue(), (String)pq.get(i).getProperty("Question"), "", (String)pq.get(i).getProperty("AnswerList")));
		}
		
		return list;
	}
	
	public List<String> getAnswerList(String answerlistid)
	{
		/*Entity alist = findAnswerListByID(answerlistid);
		List<String> list = null;
		if (alist != null){
			list = (List<String>)alist.getProperty("List");
		}*/
		fillAnswerListCache();
		return answerlistCache.get(answerlistid);
	}
	
	private Entity findQuestionByID(int id)
	{
		Query qry = new Query("AQuestion");
		qry.addFilter("QuestionID", Query.FilterOperator.EQUAL, id);
		List<Entity> pq = datastore.prepare(qry).asList(FetchOptions.Builder.withDefaults());
		Entity ent = null;
		if (!pq.isEmpty())
			ent = pq.get(0);
		return ent;
	}
	
	private Entity findAnswerListByID(String listid)
	{
		//fillTemplateQuestionCache();
		Query qry = new Query("AList");
		qry.addFilter("ListID", Query.FilterOperator.EQUAL, listid);
		List<Entity> pq = datastore.prepare(qry).asList(FetchOptions.Builder.withDefaults());
		Entity ent = null;
		if (!pq.isEmpty())
			ent = pq.get(0);
		return ent;
	}
	
	private void fillAnswerListCache()
	{
		if (answerlistCache.isEmpty()){
			Query qry = new Query("AList");
			List<Entity> pq = datastore.prepare(qry).asList(FetchOptions.Builder.withDefaults());
			for (int i = 0; i < pq.size(); i++){
				Entity ent = pq.get(i);
				Map<String, Object> props = ent.getProperties();
				answerlistCache.put((String)props.get("ListID"), (ArrayList<String>)props.get("List"));
			}
		}
	}
	
	/*private void fillTemplateQuestionCache()
	{
		if (templateqcache.isEmpty()){
			Query qry = new Query("AList");
			List<Entity> pq = datastore.prepare(qry).asList(FetchOptions.Builder.withDefaults());
			for (int i = 0; i < pq.size(); i++){
				Entity ent = pq.get(i);
				Map<String, Object> props = ent.getProperties();
				templateqcache.put((Integer)props.get("QuestionID"), new Question((Integer)props.get("QuestionID"), (String)props.get("Question"), "", (String)props.get("AnswerList")));
			}
		}
	}*/
}
